var express = require('express');
var router = express.Router();

//加载模型表
let User = require('../models/users');

//Redis
let redis = require('redis')
let client = redis.createClient()

//uuid
const uuidv4 = require('uuid/v4')   //v4是随机数

//订单号
const uuidv1 = require('uuid/v1')   //v1根据时间戳


//登录
router.post('/login', function (req, res, next) {
    let param = {
        userName: req.body.userName,
        userPwd: req.body.userPwd
    }
    User.findOne(param, (err, doc) => {
        if (err) {
            res.json({
                status: "1",
                msg: err.message
            })
        } else {
            let uuid = uuidv4()

            //存至cookie
            res.cookie("token", uuid, {
                path: "/",
                maxAge: 1000 * 60 * 60   //存储1小时
            })

            //存至redis, 1小时失效
            client.set(`token-${uuid}`, JSON.stringify(doc))
            client.expire(`token-${uuid}`, 60 * 60);

            res.json({
                status: "0",
                msg: "",
                result: {
                    nickName: doc.userName,
                    cartCount: doc.cartList.length
                }
            })
        }
    })
});

//登出
router.post('/logout', function (req, res, next) {
    let cookie = req.cookies.token
    if (cookie) {
        //清除redis
        client.del(`token-${cookie}`)
        //清除cookie
        res.cookie("token", "", {
            path: "/",
            maxAge: -1  //-1 或 0 都可以，-1就是立即执行
        })
    }
    res.json({
        status: "0",
        msg: "",
        result: ""
    })
});

//获取购物车列表
router.get("/cart", function (req, res, next) {
    let cookie = req.cookies.token
    client.get(`token-${cookie}`, (err, reply) => {
        let userId = JSON.parse(reply).userId
        User.findOne({userId: userId}, (err, doc) => {
            if (err) {
                res.json({
                    status: "1",
                    msg: err.message
                })
            } else {
                res.json({
                    status: "0",
                    msg: "",
                    result: doc.cartList
                })
            }
        })
    })
})

//购物车商品数量变更 / 选中状态变更
router.put("/cart/productChange", function (req, res, next) {
    let cookie = req.cookies.token
    let productId = req.body.productId
    let productNum = req.body.productNum
    let checkState = req.body.checkState

    client.get(`token-${cookie}`, (err, reply) => {
        let userId = JSON.parse(reply).userId
        User.update({
            userId: userId,
            "cartList.productId": productId
        }, {"cartList.$.productNum": productNum, "cartList.$.checked": checkState}, (err, doc) => {
            if (err) {
                res.json({
                    status: "1",
                    msg: err.message
                })
            } else {
                res.json({
                    status: "0",
                    msg: "",
                    result: null
                })
            }
        })
    })
})

//从购物车中删除商品
router.delete("/cart/delete/:productId", function (req, res, next) {
    let cookie = req.cookies.token
    let productId = req.param("productId")
    client.get(`token-${cookie}`, (err, reply) => {
        let userId = JSON.parse(reply).userId
        User.update({userId: userId}, {$pull: {cartList: {productId: productId}}}, (err, doc) => {
            if (err) {
                res.json({
                    status: "1",
                    msg: err.message
                })
            } else {
                res.json({
                    status: "0",
                    msg: "",
                    result: null
                })
            }
        })
    })
})

//购物车商品全选 / 取消全选
router.get("/cart/selectAll", function (req, res, next) {
    let cookie = req.cookies.token
    let selectFlag = req.param("selectFlag")
    client.get(`token-${cookie}`, (err, reply) => {
        let userId = JSON.parse(reply).userId
        User.findOne({userId: userId}, (err, doc) => {
            if (err) {
                res.json({
                    status: "1",
                    msg: err.message
                })
            } else {
                if (doc) {
                    doc.cartList.forEach(item => {
                        item.checked = selectFlag
                    })
                    doc.save((err, doc) => {
                        if (err) {
                            res.json({
                                status: "1",
                                msg: err.message
                            })
                        } else {
                            res.json({
                                status: "0",
                                msg: "",
                                result: null
                            })
                        }
                    })
                }
            }
        })
    })
})

//查询用户地址
router.get("/addressList", function (req, res, next) {
    let cookie = req.cookies.token
    client.get(`token-${cookie}`, (err, reply) => {
        let userId = JSON.parse(reply).userId
        User.findOne({userId: userId}, (err, doc) => {
            if (err) {
                res.json({
                    status: "1",
                    msg: err.message
                })
            } else {
                res.json({
                    status: "0",
                    msg: "",
                    result: doc.addressList
                })
            }
        })
    })
})

//设置默认地址
router.get("/setDetaultPath", function (req, res, next) {
    let cookie = req.cookies.token
    let addressId = req.param("addressId")
    if (!addressId) {
        return res.json({
            status: "1",
            msg: "未传入地址id"
        })
    }

    client.get(`token-${cookie}`, (err, reply) => {
        let userId = JSON.parse(reply).userId
        User.findOne({userId: userId}, (err, doc) => {
            if (err) {
                res.json({
                    status: "1",
                    msg: err.message
                })
            } else {
                doc.addressList.forEach(item => {
                    if (item.addressId == addressId) item.isDefault = true
                    else item.isDefault = false
                })
                doc.save((err, doc) => {
                    if (err) {
                        res.json({
                            status: "1",
                            msg: err.message
                        })
                    } else {
                        res.json({
                            status: "0",
                            msg: "",
                            result: true
                        })
                    }
                })
            }
        })
    })
})

//删除地址
router.delete("/delAddress", function (req, res, next) {
    let cookie = req.cookies.token
    let addressId = req.param("addressId")
    if (!addressId) {
        return res.json({
            status: "1",
            msg: "未传入地址id"
        })
    }

    client.get(`token-${cookie}`, (err, reply) => {
        let userId = JSON.parse(reply).userId
        User.update({userId: userId}, {$pull: {addressList: {addressId: addressId}}}, (err, doc) => {
            if (err) {
                res.json({
                    status: "1",
                    msg: err.message
                })
            } else {
                res.json({
                    status: "0",
                    msg: "",
                    result: null
                })
            }
        })
    })
})

//创建订单
router.post("/createOrder", function (req, res, next) {
    let cookie = req.cookies.token
    let itemSubtotal = parseFloat(req.body.itemSubtotal)    //商品总金额
    let shipping = parseFloat(req.body.shipping)         //运费
    let addressId = req.body.addressId        //收获地址id
    let goodsList = req.body.goodsList        //商品列表

    if (!addressId) {
        return res.json({
            status: "1",
            msg: "未传入地址id"
        })
    }
    if (!goodsList) {
        return res.json({
            status: "1",
            msg: "未传入商品列表"
        })
    }

    client.get(`token-${cookie}`, (err, reply) => {
        let userId = JSON.parse(reply).userId

        //重新计算订单总金额
        let totalMoney = 0;
        goodsList.forEach(item => {
            totalMoney += item.salePrice * item.productNum
        })
        if ((totalMoney + shipping) != (itemSubtotal + shipping)) {
            return res.json({
                status: "1",
                msg: "订单总金额不一致！"
            })
        }

        User.findOne({userId: userId}, (err, doc) => {
            if (err) {
                res.json({
                    status: "1",
                    msg: err.message
                })
            } else {
                let orderId = uuidv1()
                let order = {
                    orderId: orderId,
                    orderTotal: totalMoney.toFixed(2),
                    addressInfo: {},
                    goodsList: goodsList,
                    orderStatus: 0,
                    createDate: new Date()
                }

                doc.addressList.forEach(item => {
                    if (item.addressId == addressId) order.addressInfo = item
                })

                doc.orderList.push(order)

                //将购买的商品从购物车删除
                goodsList.forEach(item => {
                    let i = doc.cartList.length
                    while (i--) {
                        if (doc.cartList[i].productId == item.productId) {
                            doc.cartList.splice(i, 1);
                        }
                    }
                })

                doc.save((err1, doc1) => {
                    if (err1) {
                        res.json({
                            status: "1",
                            msg: err1.message
                        })
                    } else {
                        res.json({
                            status: "0",
                            msg: "",
                            result: {
                                orderId: orderId,
                                cartCount: doc1.cartList.length

                            }
                        })
                    }
                })
            }
        })
    })
})


//查询订单信息
router.get("/getOrderInfo", function (req, res, next) {
    let cookie = req.cookies.token
    let orderId = req.param("orderId")

    if (!orderId) {
        return res.json({
            status: "1",
            msg: "未传入订单号"
        })
    }

    client.get(`token-${cookie}`, (err, reply) => {
        let userId = JSON.parse(reply).userId
        User.findOne({userId: userId}, (err, user) => {
            if (err) {
                res.json({
                    status: "1",
                    msg: err.message
                })
            } else {
                user.orderList.forEach(item => {
                    if (item.orderId == orderId) {
                        return res.json({
                            status: "0",
                            msg: "",
                            result: {
                                orderId: item.orderId,
                                orderTotal: item.orderTotal
                            }
                        })
                    }
                })
            }
        })
    })
})

//检查登录状态，返回用户名和购物车商品数量
router.get("/checkLogin", function (req, res, next) {
    let cookie = req.cookies.token
    client.get(`token-${cookie}`, (err, reply) => {
        let userId = JSON.parse(reply).userId
        User.findOne({userId: userId}, (err, user) => {
            if (err) {
                res.json({
                    status: "1",
                    msg: err.message
                })
            } else {
                res.json({
                    status: "0",
                    msg: "",
                    result: {
                        nickName: user.userName,
                        cartCount: user.cartList.length
                    }
                })
            }
        })
    })
})


module.exports = router;
